package com.echo.boot.design.turing.flyweight;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/8/9
 * Time: 21:54
 * 享元模式
 * 运用共享技术有效的支持大量细粒度的对象
 *
 * @author Administrator
 */
public class Flyweight {
    public static void main(String[] args) {
        new Thread(() -> {
            new TreeNode(0, 5, TreeFactory.getTree("p", "data"));
        }).start();
        new Thread(() -> {
            new TreeNode(4, 8, TreeFactory.getTree("p", "data"));
        }).start();
        new Thread(() -> {
            new TreeNode(4, 8, TreeFactory.getTree("p", "data"));
        }).start();
    }
}

class TreeFactory {
    private static final ConcurrentHashMap<String, Tree> MAP = new ConcurrentHashMap<>();

    public static Tree getTree(String name, String data) {
        Tree tree = null;
        if (MAP.containsKey(name)) {
            tree = MAP.get(name);
            System.out.println(tree);
            return MAP.get(name);
        }
        tree = new Tree(name, data);
        MAP.put(name, tree);
        System.out.println(tree);
        return tree;
    }

}

class TreeNode {
    private Integer x;
    private Integer y;
    private Tree tree;

    public TreeNode(Integer x, Integer y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }
}

class Tree {
    private final String treeName;
    private final String treeData;

    public Tree(String treeName, String treeData) {
        this.treeName = treeName;
        this.treeData = treeData;
    }

    @Override
    public String toString() {
        return this.hashCode() + " Tree{" +
                "treeName='" + treeName + '\'' +
                ", treeData='" + treeData + '\'' +
                '}';
    }
}
